module.exports = (app) => {
  const { Schema, model, getModelName, formatDate } = app.jax.mongoose
  const modelName = getModelName(__filename)

  const CacheSchema = new Schema({
    key: String,
    value: String,
    time: Number, // 缓存时间(毫秒)
    expire: { type: Date, get: (date) => formatDate(date) }, // 过期时间
  })

  // 获取过期时间
  const getExpire = (data) => {
    const time = data.time || 60 * 1000
    const date = new Date(Date.now() + time)
    return date
  }

  CacheSchema.pre(['updateOne', 'findOneAndUpdate', 'updateMany'], async function () {
    const data = this.getUpdate()
    data.expire = getExpire(data)
  })

  CacheSchema.pre('save', async function () {
    this.expire = getExpire(this)
  })

  const Model = model(modelName, CacheSchema)

  return Model
}
